<?php

namespace main {

	use C\ctr;
	use C\lib\Aes;
	use C\lib\Db;
	use C\lib\Net;
	use C\lib\Rsa;
    use C\lib\Session;
    use C\lib\Sms;
	use C\lib\Text;
	use C\mod\code;
	use C\mod\express;
	use C\mod\proute;
	use C\mod\user;
	use C\mod\worker;
	use C\mod\wprice;
	use C\mod\order;
	use C\lib\Wxapi;
	use C\mod\workerd;
	use C\lib\Ditu;
	use C\lib\Jpush;
    use C\mod\sms_routing;
    use C\mod\voucher;
    use C\mod\tui;

	class main extends ctr {




		public function main() {
Db::connect();
            $sql = new Sql();
            $sql->select('*', static::$__table_s)->append(' WHERE sqrt((((' . ($lng + 0) . '-lng)*PI()*12656*cos(((' . ($lat + 0) . '+lat)/2)*PI()/180)/180)*((' . ($lng + 0) . '-lng)*PI()*12656*cos(((' . ($lat + 0) . '+lat)/2)*PI()/180)/180))+(((' . ($lat + 0) . '-lat)*PI()*12656/180)*((' . ($lat + 0) . '-lat)*PI()*12656/180)))<2 AND state='.$state.'');
            if ($ps = Db::query($sql->sql)) {
                $list = [];
                while ($o = $ps->fetchObject(static::class))
                    $list[] = $o;
                if($list){
                    foreach ($list as $value){

                    }
                }
                return $list;
            } else
                return false;

		}

        /*
         * 推送消息
         * ptype:1 普通快递 2物流托运？？？？？取快递要不要推送  给谁推送
         * type:1快递员 0取递员
         * wtype:消息分类推送(顺丰 三通一达 优速 百世物流 德邦物流)
         * distance:推送范围 (周围公里)
         */
        private function pushInfo($ptype,$type,$lat,$lng,$distance,$wtype){
            //满足推送条件的推送
            //查询到在燕丹区域内的快递员
            //$distance=2;
//            $lat='40.024199';
//            $lng='116.301271';
            $stype=[];
            if(!empty($ptype)){
                if($ptype==1){
                    if($wtype==1){
                        $stype=['顺丰'];
                    }
                    if($wtype==2){
                        $stype=['中通','申通','圆通','韵达'];
                    }
                    if($wtype==3){
                        $stype=['优速'];
                    }
                }
                if($ptype==2){
                    //$stype=['百世物流','德邦物流'];
                    if($wtype==5){
                        $stype=['百世物流'];
                    }
                    if($wtype==6){
                        $stype=['德邦物流'];
                    }
                }
            }
            // echo 555;//exit;
            //获取用户周围n公里内的快递员(取递员)
            //如果附近有快递员推送 没有则返回0  推送成功返回1 不成功返回0
            $list=worker::scop($lat,$lng,$distance);

            //  print_r($list);//exit;
            //var_dump($list);exit;
            if($list){
                $m_time = '600';//离线保留时间
                $tag= [];
                foreach ($list as $val){
                    if($type==0){//代取员 (1)先根据工人类型判断推送目标
                        $workerd=workerd::get(['worker_id'=>$val->id,'type'=>0]);
                        //var_dump($workerd);
                        if($workerd){
                            //查询是否缴纳押金  交押金的推送  (2)是否要根据学校名 或负责的代取位置进行推送????

                            $wprice=wprice::get(['pay_state'=>1,'worker_id'=>$workerd->worker_id]);
                            // var_dump($wprice);

                            if($wprice){
                                $tag[]=$wprice->worker_id;
                            }
                        }
                    }else{//快递物流

                        //判断  那一部分需要推送 需要推送的是否交过押金
                        $workerd=workerd::get(['worker_id'=>$val->id,['subsidiary','in',$stype]]);
                        //var_dump($workerd);//exit;
                        //var_dump($workerd->worker_id);//exit;
                        if($workerd){
                            $wprice=wprice::get(['pay_state'=>1,'worker_id'=>$workerd->worker_id]);
                            if($wprice){
                                $tag[]=$wprice->worker_id;
                            }
                        }
                    }
                }
                //var_dump($tag);//exit;
                // echo 333;

                if(!empty($tag)){
                    //var_dump($tag);exit;
                    //$content='您有一个订单是否要接单:'.$name.'电话:'.$phone.'预约寄件时间为:'.$time;
                    if($type==1){
                        $content='您有一寄快递个订单';
                    }else{
                        $content='您有一个代取快递订单';
                    }

                    $message="";//存储推送状态
                    $result = Jpush::push('all',$content,'','',$m_time,$tag);


                    $res_arr = json_decode($result, true);
                    if(isset($res_arr['error'])){
                        if($res_arr['error']['code']==200){
                            foreach($tag as $value){
                                $tui=new tui();
                                $tui->set([
                                    'wid'=>$value,
                                    'time_add'=>time()
                                ]);
                                $tui->create();
                            }
                        }
                    }else{
                        foreach($tag as $value){
                            $tui=new tui();
                            $tui->set([
                                'wid'=>$value,
                                'time_add'=>time()
                            ]);
                            $tui->create();
                        }
                    }


                    if($result){
                        $res_arr = json_decode($result, true);
                        if(isset($res_arr['error'])){                       //如果返回了error则证明失败
                            //echo $res_arr['error']['message'];          //错误信息
                            $error_code=$res_arr['error']['code'];             //错误码
                            switch ($error_code) {
                                case 200:
                                    $message= '发送成功！';
                                    // $message;
                                    return true;
                                    break;
                                case 1000:
                                    $message= '失败(系统内部错误)';
                                    // echo $message;
                                    return false;
                                    break;
                                case 1001:
                                    $message = '失败(只支持 HTTP Post 方法，不支持 Get 方法)';//echo $message;
                                    return false;
                                    break;
                                case 1002:
                                    $message= '失败(缺少了必须的参数)';//echo $message;
                                    return false;
                                    break;
                                case 1003:
                                    $message= '失败(参数值不合法)';//echo $message;
                                    return false;
                                    break;
                                case 1004:
                                    $message= '失败(验证失败)';//echo $message;
                                    return false;
                                    break;
                                case 1005:
                                    $message= '失败(消息体太大)';//echo $message;
                                    return false;
                                    break;
                                case 1008:
                                    $message= '失败(appkey参数非法)';//echo $message;
                                    return false;
                                    break;
                                case 1011:
                                    $message= '没有满足条件的推送对象';//echo $message;
                                    return false;
                                    break;
                                case 1020:
                                    $message= '失败(只支持 HTTPS 请求)';//echo $message;
                                    return false;
                                    break;
                                case 1030:
                                    $message= '失败(内部服务超时)';//echo $message;
                                    return false;
                                    break;
                                default:
                                    $message= '失败(返回其他状态，目前不清楚额，请联系开发人员！)';//echo $message;
                                    return false;
                                    break;
                            }
                        }else{
                            $message="发送成功！";//echo $message;
                            return true;
                        }
                    }else{
                        $message='接口调用失败或无响应';//echo $message;
                        return false;
                    }
                    //echo  "<script>alert('推送信息:{$message}')</script>";

                }else{
                    return false;
                }
            }else{
                return false;
            }

        }


		public static function getExpressMsg($url , $options = array()) {
			//快递

			$options[CURLOPT_RETURNTRANSFER] = true;
			$options[CURLOPT_TIMEOUT] = 5;
			$options[CURLOPT_REFERER] =  'http://www.kuaidi100.com/';
			$options[CURLOPT_USERAGENT] = 'www.kuaidi100.com/';
			$ch = curl_init($url);
			curl_setopt_array($ch,$options);
			$html = curl_exec($ch);
			curl_close($ch);
			return $html;
		}

		public function test() {
			$url = 'http://www.kuaidi100.com/query?type=yuantong&postid=886544364750024948&id=19&valicode=&temp='.mt_getrandmax();
			$express = json_decode(self::getExpressMsg($url) ,true);

			if(isset($express['data']) && ($express['message'] === 'ok')) {
				var_dump($express['data']['0']['context']);
			}
			if(strpos($express['data']['0']['context'],'已签收')){
				echo 1;
			}else{
				echo 2;exit();
			}


			exit();
		echo 1;
			//Sms::send('13816434372', '曹操到技术部祝您工作顺利,身体健康!');

		}

	}

	class wechatCallbackapiTest
	{
		//验证签名
		public function valid() {
			$echoStr = $_GET["echostr"];
			$signature = $_GET["signature"];
			$timestamp = $_GET["timestamp"];
			$nonce = $_GET["nonce"];
			$token = TOKEN;
			$tmpArr = array($token, $timestamp, $nonce);
			sort($tmpArr);
			$tmpStr = implode($tmpArr);
			$tmpStr = sha1($tmpStr);
			if($tmpStr == $signature){
				header('content-type:text');
				echo $echoStr;
				exit;
			}
		}

		//响应消息
		public function responseMsg() {
			$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
			if (!empty($postStr)){
				$this->logger("R ".$postStr);
				$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
				$RX_TYPE = trim($postObj->MsgType);

				//消息类型分离
				switch ($RX_TYPE) {
					case "event":
						$result = $this->receiveEvent($postObj);
						break;
					case "text":
						$result = $this->receiveText($postObj);
						break;
					case "image":
						$result = $this->receiveImage($postObj);
						break;
					case "location":
						$result = $this->receiveLocation($postObj);
						break;
					case "voice":
						$result = $this->receiveVoice($postObj);
						break;
					case "video":
						$result = $this->receiveVideo($postObj);
						break;
					case "link":
						$result = $this->receiveLink($postObj);
						break;
					default:
						$result = "unknown msg type: ".$RX_TYPE;
						break;
				}
				$this->logger("T ".$result);
				echo $result;
			}else {
				echo "";
				exit;
			}
		}

		//接收事件消息
		private function receiveEvent($object)
		{
			$content = "";
			switch ($object->Event)
			{
				case "subscribe":
					$content = "欢迎关注曹操到工作室 ";
					$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
					break;
				case "unsubscribe":
					$content = "取消关注";
					break;
				case "SCAN":
					$content = "扫描场景 ".$object->EventKey;
					break;
				case "CLICK":
					switch ($object->EventKey)
					{
						case "COMPANY":
							$content = array();
							$content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
							break;
						default:
							$content = "点击菜单：".$object->EventKey;
							break;
					}
					break;
				case "LOCATION":
					$content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
					break;
				case "VIEW":
					$content = "跳转链接 ".$object->EventKey;
					break;
				case "MASSSENDJOBFINISH":
					$content = "消息ID：".$object->MsgID."，结果：".$object->Status."，粉丝数：".$object->TotalCount."，过滤：".$object->FilterCount."，发送成功：".$object->SentCount."，发送失败：".$object->ErrorCount;
					break;
				default:
					$content = "receive a new event: ".$object->Event;
					break;
			}
			if(is_array($content)){
				if (isset($content[0])){
					$result = $this->transmitNews($object, $content);
				}else if (isset($content['MusicUrl'])){
					$result = $this->transmitMusic($object, $content);
				}
			}else{
				$result = $this->transmitText($object, $content);
			}

			return $result;
		}

		//接收文本消息
		private function receiveText($object)
		{
			$keyword = trim($object->Content);
			//多客服人工回复模式
			if (strstr($keyword, "您好") || strstr($keyword, "你好") || strstr($keyword, "在吗")){
				$result = $this->transmitService($object);

			}
			//自动回复模式
			else{
				if (strstr($keyword, "文本")){
					$content = "这是个文本消息";
				}else if (strstr($keyword, "单图文")){
					$content = array();
					$content[] = array("Title"=>"单图文标题",  "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
				}else if (strstr($keyword, "快递") || strstr($keyword, "查快递")){
					$content = array();
					$content[] = array("Title"=>"曹操去哪了", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"");
					$content[] = array("Title"=>"曹操在路上", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"");
					$content[] = array("Title"=>"曹操快来", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"");
				}else if (strstr($keyword, "音乐")){
					$content = array();
					$content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
				}else{

					$content = date("Y年m月d日 H:i:s",time());
				}

				if(is_array($content)){
					if (isset($content[0]['PicUrl'])){
						$result = $this->transmitNews($object, $content);
					}else if (isset($content['MusicUrl'])){
						$result = $this->transmitMusic($object, $content);
					}
				}else{
					$result = $this->transmitText($object, $content);
				}
			}

			return $result;
		}

		//接收图片消息
		private function receiveImage($object)
		{
			$content = array("MediaId"=>$object->MediaId);
			$result = $this->transmitImage($object, $content);
			return $result;
		}

		//接收位置消息
		private function receiveLocation($object)
		{
			$content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
			$result = $this->transmitText($object, $content);
			return $result;
		}

		//接收语音消息
		private function receiveVoice($object)
		{
			if (isset($object->Recognition) && !empty($object->Recognition)){
				$content = "你刚才说的是：".$object->Recognition;
				$result = $this->transmitText($object, $content);
			}else{
				$content = array("MediaId"=>$object->MediaId);
				$result = $this->transmitVoice($object, $content);
			}

			return $result;
		}

		//接收视频消息
		private function receiveVideo($object)
		{
			$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
			$result = $this->transmitVideo($object, $content);
			return $result;
		}

		//接收链接消息
		private function receiveLink($object)
		{
			$content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
			$result = $this->transmitText($object, $content);
			return $result;
		}

		//回复文本消息
		private function transmitText($object, $content)
		{
			$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
			$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
			return $result;
		}

		//回复图片消息
		private function transmitImage($object, $imageArray)
		{
			$itemTpl = "<Image>
    <MediaId><![CDATA[%s]]></MediaId>
</Image>";

			$item_str = sprintf($itemTpl, $imageArray['MediaId']);

			$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

			$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
			return $result;
		}

		//回复语音消息
		private function transmitVoice($object, $voiceArray)
		{
			$itemTpl = "<Voice>
    <MediaId><![CDATA[%s]]></MediaId>
</Voice>";

			$item_str = sprintf($itemTpl, $voiceArray['MediaId']);

			$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";

			$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
			return $result;
		}

		//回复视频消息
		private function transmitVideo($object, $videoArray)
		{
			$itemTpl = "<Video>
    <MediaId><![CDATA[%s]]></MediaId>
    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
</Video>";

			$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

			$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";

			$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
			return $result;
		}

		//回复图文消息
		private function transmitNews($object, $newsArray)
		{
			if(!is_array($newsArray)){
				return;
			}
			$itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
			$item_str = "";
			foreach ($newsArray as $item){
				$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
			}
			$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

			$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
			return $result;
		}

		//回复音乐消息
		private function transmitMusic($object, $musicArray)
		{
			$itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

			$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

			$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

			$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
			return $result;
		}

		//回复多客服消息
		private function transmitService($object)
		{
			$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
			$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
			return $result;
		}

		//日志记录
		private function logger($log_content)
		{
			if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
				sae_set_display_errors(false);
				sae_debug($log_content);
				sae_set_display_errors(true);
			}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
				$max_size = 10000;
				$log_filename = "log.xml";
				if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
				file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
			}
		}
	}


}

